package com.gsbelarus.gedemin.salary;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.support.multidex.MultiDex;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.lib.sync.protocol.AlarmReceiver;
import com.gsbelarus.gedemin.lib.ui.GedeminApplication;
import com.gsbelarus.gedemin.salary.fragment.SettingsFragment;
import com.gsbelarus.gedemin.salary.receiver.AutoSyncReceiver;
import com.gsbelarus.gedemin.salary.util.CurrencyHelper;

import java.util.HashMap;
import java.util.Locale;

public class App extends GedeminApplication {

    private static Context mContext;

    /**
     * Enum used to identify the tracker that needs to be used for tracking.
     * <p/>
     * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
     * storing them all in Application object helps ensure that they are created only once per
     * application instance.
     */
    public enum TrackerName {
        APP_TRACKER //, GLOBAL_TRACKER
    }

    private static HashMap<TrackerName, Tracker> mTrackers = new HashMap<>();

    public static synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(getContext());
            Tracker t = //(trackerId == TrackerName.APP_TRACKER) ?
                    analytics.newTracker(R.xml.analytics_app_tracker);
            mTrackers.put(trackerId, t);
        }
        return mTrackers.get(trackerId);
    }

    /**
     * Получение AlarmReceiver. Служит для создания синхронизации по расписанию.
     * Для работы необходимо расширить класс AlarmReceiver, написать логику и <ВАЖНО!> прописать receiver в AndroidManifest.xml </ВАЖНО!>
     *
     * @return AlarmReceiver
     */
    @Override
    public AlarmReceiver getAlarmReceiver() {
        return new AutoSyncReceiver();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        changeLocale();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //Fabric.with(this, new Crashlytics());

        changeLocale();
        mContext = this;
        CurrencyHelper.getInstance(getApplicationContext()).updatesRates(null);
    }

    public static Context getContext() {
        return mContext;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this); //TODO
    }

    private String getPrefLang() {
        SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(getBaseContext());
        return getResources().getStringArray(R.array.language_list_values)
                [pref.getInt(SettingsFragment.LANG_PREF, SettingsFragment.DEFAULT_LANG_PREF_ITEM)];
    }

    public void changeLocale() {
        Configuration config = getBaseContext().getResources().getConfiguration();
        String lang = getPrefLang();
        if (!config.locale.getLanguage().equals(lang)) {
            Locale locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config,
                    getBaseContext().getResources().getDisplayMetrics());
        }
    }
}
